﻿Imports MICROFORMA.BEL
Imports MICROFORMA.DIL
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Data.Common

Public Class RolOpcionDA
    Implements RolOpcionDI

    Public Function List(ByVal _IdRol As Int16) As RolOpcionBECollection Implements DIL.RolOpcionDI.List

        Dim dr As DbDataReader = Nothing

        Dim o_BECollec_RolOpcion_BE As New RolOpcionBECollection

        Dim o_RolOpcion_BE As RolOpcionBE

        Dim db As Database = DatabaseFactory.CreateDatabase()

        Dim query As String = "select * from RolOpcion where idrol=" & _IdRol & "and estado=0"

        Dim dbCommand As DbCommand = db.GetSqlStringCommand(query)

        dr = db.ExecuteReader(dbCommand)

        While dr.Read()
            o_RolOpcion_BE = New RolOpcionBE
            o_RolOpcion_BE.IdRol = dr("IdRol")
            o_RolOpcion_BE.IdPermiso = dr("IdPermiso")
            o_RolOpcion_BE.Estado = dr("Estado")
            o_RolOpcion_BE.FechaCreacion = dr("FechaCreacion")
            o_RolOpcion_BE.FechaModificacion = dr("FechaModificacion")

            o_BECollec_RolOpcion_BE.Add(o_RolOpcion_BE)
            o_RolOpcion_BE = Nothing
        End While

        Return o_BECollec_RolOpcion_BE

    End Function

    Public Function Add(ByVal _RolOpcionCollection As ArrayList, Optional ByVal idRol As Int16 = Nothing) As String Implements DIL.RolOpcionDI.Add

        Dim db As Database = DatabaseFactory.CreateDatabase()

        Dim o_Cnx As DbConnection = db.CreateConnection()

        o_Cnx.Open()

        Dim o_Transaction As DbTransaction = o_Cnx.BeginTransaction


        Try

            Dim query As String = "delete from RolOpcion where idRol= " & idRol

            Dim o_dbCommand As DbCommand = db.GetSqlStringCommand(query)

            db.ExecuteNonQuery(o_dbCommand, o_Transaction)

            For index As Integer = 0 To _RolOpcionCollection.Count - 1
                query = "insert into RolOpcion (idRol,idPermiso) " & _
                        "values ('" & idRol & "','" & _RolOpcionCollection(index) & "')"

                db.ExecuteNonQuery(o_Transaction, CommandType.Text, query)
            Next

            o_Transaction.Commit()

            Return "OK"

        Catch ex As Exception
            o_Transaction.Rollback()
            Return ex.Message.ToString
        Finally
            o_Cnx.Close()

        End Try
    End Function

End Class
